package paidaxing.blog.core.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import paidaxing.blog.core.dto.SearchRecordDTO;
import paidaxing.blog.core.entity.SearchRecords;
import paidaxing.blog.core.mapper.SearchRecordsMapper;
import paidaxing.blog.core.service.SearchRecordsService;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SearchRecordsServiceImpl implements SearchRecordsService {

    @Resource
    private SearchRecordsMapper searchRecordsMapper;

    @Override
    public boolean recordSearch(String keyword, Long userId) {
        // 检查关键词是否已存在
        SearchRecords existingRecord = searchRecordsMapper.queryByKeyword(keyword);
        if (existingRecord != null) {
            // 增加搜索次数
            int result = searchRecordsMapper.incrementSearchCount(keyword);
            return result > 0;
        } else {
            // 创建新的搜索记录
            SearchRecords searchRecord = new SearchRecords();
            searchRecord.setKeyword(keyword);
            searchRecord.setSearchCount(1);
            searchRecord.setUserId(userId);
            searchRecord.setCreatedAt(new Date());
            searchRecord.setUpdatedAt(new Date());
            
            int result = searchRecordsMapper.insert(searchRecord);
            return result > 0;
        }
    }

    @Override
    public List<SearchRecordDTO> getHotSearches(int limit) {
        List<SearchRecords> searchRecordsList = searchRecordsMapper.queryHotSearches(limit);
        return searchRecordsList.stream().map(searchRecord -> {
            SearchRecordDTO dto = new SearchRecordDTO();
            BeanUtils.copyProperties(searchRecord, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<SearchRecordDTO> getSearchRecordsByDateRange(Date startDate, Date endDate) {
        List<SearchRecords> searchRecordsList = searchRecordsMapper.queryByDateRange(startDate, endDate);
        return searchRecordsList.stream().map(searchRecord -> {
            SearchRecordDTO dto = new SearchRecordDTO();
            BeanUtils.copyProperties(searchRecord, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public SearchRecordDTO getSearchRecordByKeyword(String keyword) {
        SearchRecords searchRecord = searchRecordsMapper.queryByKeyword(keyword);
        if (searchRecord == null) {
            return null;
        }
        
        SearchRecordDTO dto = new SearchRecordDTO();
        BeanUtils.copyProperties(searchRecord, dto);
        return dto;
    }
}